package com.example.login.mvvm.viewmodel

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.example.login.api.LoginApiManager
import com.google.gson.reflect.TypeToken
import com.gsafety.library.Base.BaseViewModel
import com.gsafety.libraryktx.bean.LoadState
import com.gsafety.libraryktx.bean.LoginBean
import com.gsafety.libraryktx.expand.enqueue
import com.gsafety.libraryktx.manager.UserManager
import com.gsafety.libraryktx.net.api.request.RequestParamsManager
import kotlin.collections.ArrayList


/**
 * @author : lj
 * @date : 2020/9/23 16:53
 */
class LoginViewModel: BaseViewModel(){
    var loadState = MutableLiveData<LoadState>()

    fun requestlogin(userName: String, pwd: String){
        loadState.value = LoadState.Loading()
        enqueue(LoginApiManager.apiService.login(RequestParamsManager.login(userName,pwd)),onSuccess={ result ->
            result?.let {
                switchdata(it)
            }
            loadState.value = LoadState.Success()
        },onFail={ error->
            loadState.value = LoadState.Fail(error?: "")

        })
    }

     fun switchdata(data:String){
        var map=GsonUtils.fromJson(data,Map::class.java)
        var login=LoginBean()
        login.sessionId= map["sessionId"].toString()
        var ssoSysUser=GsonUtils.fromJson(GsonUtils.toJson(map["ssoSysUser"]),Map::class.java)
        login.userId=ssoSysUser["userId"].toString()
        login.userName=ssoSysUser["userName"].toString()
         login.email=ssoSysUser["email"].toString()
         login.phone=ssoSysUser["phone"].toString()
        var currAuths=GsonUtils.fromJson(GsonUtils.toJson(ssoSysUser["currAuths"]),Map::class.java)
        var currRolesType=object : TypeToken<List<Map<String,String>>>(){}.type
        var currRoles=GsonUtils.fromJson<ArrayList<Map<String,String>>>(GsonUtils.toJson(ssoSysUser["currRoles"]),currRolesType)
        var role=currRoles[0]["roleCode"]
        var roles=GsonUtils.fromJson<ArrayList<Map<String,String>>>(GsonUtils.toJson(currAuths[role]),currRolesType)
        var extdsInfos=GsonUtils.fromJson(GsonUtils.toJson(ssoSysUser["extdsInfos"]),Map::class.java)
         var orgType=extdsInfos["orgType"].toString()
         var orgName=extdsInfos["orgName"].toString()
        var codes=ArrayList<String>()
        roles?.forEach {
            codes.add(it["relRscCode"].toString())
        }
        login.appModelCodes=codes
        login.orgType=orgType
        login.orgName=orgName
        UserManager.getInstance().putLogin(login)

    }



}